import React, { useEffect, useMemo, useRef, useState } from 'react'

type Role = 'user' | 'sales' | 'supplier'

type Message = {
  id: string
  role: Role
  type: 'text' | 'form'
  content: string
  extra?: any
  timestamp: string
}

const API_BASE = import.meta.env.VITE_API_BASE || 'http://127.0.0.1:8000'

export const App: React.FC = () => {
  const [role, setRole] = useState<Role>('user')
  const [messages, setMessages] = useState<Message[]>([])
  const [lastError, setLastError] = useState<string | null>(null)
  const [input, setInput] = useState('')
  const scrollRef = useRef<HTMLDivElement | null>(null)

  const roleLabel = useMemo(() => ({ user: '用户', sales: '销售', supplier: '供应商' }[role]), [role])

  const fetchMessages = async () => {
    try {
      const res = await fetch(`${API_BASE}/messages?role=${role}`, { method: 'GET', mode: 'cors' })
      if (!res.ok) throw new Error(`messages ${res.status}`)
      const data = await res.json()
      setMessages(data.items || [])
      setLastError(null)
    } catch (e: any) {
      console.error('fetchMessages error', e)
      setLastError(e?.message || '消息拉取失败')
    }
  }

  useEffect(() => {
    fetchMessages()
    const t = setInterval(fetchMessages, 1500)
    return () => clearInterval(t)
  }, [role])

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: 999999, behavior: 'smooth' })
  }, [messages])

  const sendText = async () => {
    if (!input.trim()) return
    try {
      const res = await fetch(`${API_BASE}/chat`, {
        method: 'POST',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role, content: input })
      })
      if (!res.ok) throw new Error(`chat ${res.status}`)
      await res.json()
      setInput('')
      fetchMessages()
      setLastError(null)
    } catch (e: any) {
      console.error('sendText error', e)
      setLastError(e?.message || '发送失败')
    }
  }

  const triggerAction = async (action: string, params?: any) => {
    try {
      const res = await fetch(`${API_BASE}/action`, {
        method: 'POST',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role, action, params })
      })
      if (!res.ok) throw new Error(`action ${res.status}`)
      await res.json()
      fetchMessages()
      setLastError(null)
    } catch (e: any) {
      console.error('triggerAction error', e)
      setLastError(e?.message || '操作失败')
    }
  }

  const renderForm = (m: Message) => {
    const extra = m.extra || {}
    if (extra.formType === 'selectProduct') {
      return (
        <SelectProduct options={extra.options || []} onSubmit={(productId) => triggerAction(extra.submitAction, { productId })} />
      )
    }
    if (extra.formType === 'salesConfirm') {
      return (
        <button className="btn" onClick={() => triggerAction(extra.submitAction, { orderId: extra.orderId })}>确认下给供应商</button>
      )
    }
    if (extra.formType === 'supplierShip') {
      return <SupplierShip onSubmit={(company, trackingNo) => triggerAction(extra.submitAction, { company, trackingNo })} />
    }
    return null
  }

  return (
    <div className="page">
      <header>
        <h2>AI SRM Demo</h2>
        <div className="roles">
          {(['user', 'sales', 'supplier'] as Role[]).map(r => (
            <button key={r} className={`tab ${r === role ? 'active' : ''}`} onClick={() => setRole(r)}>
              {({ user: '用户', sales: '销售', supplier: '供应商' } as any)[r]}
            </button>
          ))}
        </div>
        <span className="api">API: {API_BASE}</span>
      </header>

      {lastError && <div className="error">{lastError}</div>}

      <div className="chat" ref={scrollRef}>
        {messages.map(m => (
          <div key={m.id} className={`msg ${m.role}`}>
            <div className="meta">{m.role === 'user' ? '用户' : m.role === 'sales' ? '销售' : '供应商'} · {new Date(m.timestamp).toLocaleString()}</div>
            <div className="bubble">
              <div className="text">{m.content}</div>
              {m.type === 'form' && (
                <div className="form">{renderForm(m)}</div>
              )}
            </div>
          </div>
        ))}
      </div>

      <footer>
        <input value={input} onChange={e => setInput(e.target.value)} placeholder={`以${roleLabel}身份发送消息...`} onKeyDown={e => e.key === 'Enter' && sendText()} />
        <button onClick={sendText}>发送</button>
      </footer>

      <style>{css}</style>
    </div>
  )
}

const SelectProduct: React.FC<{ options: { label: string, value: string }[], onSubmit: (pid: string) => void }> = ({ options, onSubmit }) => {
  const [pid, setPid] = useState(options[0]?.value || '')
  useEffect(() => { if (options.length) setPid(options[0].value) }, [options])
  return (
    <div className="form-row">
      <select value={pid} onChange={e => setPid(e.target.value)}>
        {options.map(op => <option key={op.value} value={op.value}>{op.label}</option>)}
      </select>
      <button className="btn" onClick={() => onSubmit(pid)}>下单</button>
    </div>
  )
}

const SupplierShip: React.FC<{ onSubmit: (company: string, trackingNo: string) => void }> = ({ onSubmit }) => {
  const [company, setCompany] = useState('顺丰速运')
  const [trackingNo, setTrackingNo] = useState('')
  return (
    <div className="form-col">
      <input placeholder="快递公司" value={company} onChange={e => setCompany(e.target.value)} />
      <input placeholder="快递单号" value={trackingNo} onChange={e => setTrackingNo(e.target.value)} />
      <button className="btn" onClick={() => onSubmit(company, trackingNo)}>提交发货</button>
    </div>
  )
}

const css = `
  * { box-sizing: border-box; }
  body, html, #root { height: 100%; margin: 0; }
  .page { height: 100%; display: flex; flex-direction: column; font-family: Inter, system-ui, Arial; }
  header { padding: 12px 16px; border-bottom: 1px solid #eee; display: flex; align-items: center; justify-content: space-between; }
  .roles { display: flex; gap: 8px; }
  .tab { padding: 6px 12px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; }
  .tab.active { background: #111; color: #fff; border-color: #111; }
  .chat { flex: 1; overflow: auto; padding: 16px; background: #f6f7f9; }
  .api { font-size: 12px; color: #999; margin-left: 12px; }
  .msg { margin-bottom: 12px; max-width: 720px; }
  .msg.user .bubble { background: #fff; }
  .msg.sales .bubble { background: #fffaf0; }
  .msg.supplier .bubble { background: #f0fff5; }
  .meta { color: #666; font-size: 12px; margin: 4px 2px; }
  .bubble { padding: 10px 12px; border-radius: 10px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
  .text { margin-bottom: 8px; white-space: pre-wrap; }
  footer { padding: 12px 16px; border-top: 1px solid #eee; display: flex; gap: 8px; }
  footer input { flex: 1; padding: 8px 10px; border: 1px solid #ddd; border-radius: 8px; }
  footer button, .btn { padding: 8px 12px; border: 1px solid #111; background: #111; color: #fff; border-radius: 8px; cursor: pointer; }
  .form { margin-top: 6px; }
  .form-row { display: flex; gap: 8px; align-items: center; }
  .form-col { display: flex; gap: 8px; flex-direction: column; }
  .error { background: #ffecec; color: #b00020; padding: 8px 12px; border: 1px solid #ffb3b3; margin: 8px 16px; border-radius: 8px; }
`


